<template>
  <view class="login-container">
    <!-- 顶部背景装饰 -->
    <view class="login-header">
      <image class="header-bg" src="@/static/sunflower.jpg" mode="aspectFill"></image>
      <view class="header-overlay"></view>
      
      <text class="slogan">遇见美好，绽放生活</text>
    </view>

    <!-- 切换标签 -->
    <view class="tab-container">
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'login' }"
        @tap="switchTab('login')"
      >
        <text>登录</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 'register' }"
        @tap="switchTab('register')"
      >
        <text>注册</text>
      </view>
      <view class="tab-line" :style="{ transform: `translateX(${currentTab === 'login' ? 0 : '100%'})` }"></view>
    </view>

    <!-- 表单区域 -->
    <swiper class="form-swiper" :current="currentTab === 'login' ? 0 : 1" @change="handleSwiperChange">
      <!-- 登录表单 -->
      <swiper-item>
        <view class="form-container">
          <view class="input-group">
            <text class="input-label">邮箱账号</text>
            <input 
              class="input-field" 
              type="text"
              v-model="loginForm.email"
              placeholder="请输入邮箱账号"
            />
          </view>
          <view class="input-group">
            <text class="input-label">登录密码</text>
            <input 
              class="input-field" 
              type="password" 
              v-model="loginForm.password"
              placeholder="请输入密码"
            />
          </view>
          <view class="form-actions">
            <text class="forget-pwd" @tap="handleForgetPassword">忘记密码？</text>
          </view>
          <button class="submit-btn" @tap="handleLogin">登 录</button>
          <view class="other-login">
            <view class="divider">
              <text class="divider-text">其他登录方式</text>
            </view>
            <view class="social-login">
              <view class="social-item">
                <image src="@/static/c1.png" mode="aspectFit"></image>
                <text>微信</text>
              </view>
              <view class="social-item">
                <image src="@/static/c2.png" mode="aspectFit"></image>
                <text>QQ</text>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>

      <!-- 注册表单 -->
      <swiper-item>
        <view class="form-container">
          <view class="input-group">
            <text class="input-label">邮箱账号</text>
            <input 
              class="input-field" 
              type="text"
              v-model="registerForm.email"
              placeholder="请输入邮箱账号"
            />
          </view>
          <view class="input-group verification">
            <input 
              class="input-field" 
              type="text" 
              v-model="registerForm.code"
              placeholder="请输入验证码"
              maxlength="6"
            />
            <button 
              class="verify-btn" 
              :disabled="countdown > 0"
              @tap="handleSendCode"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
            </button>
          </view>
          <view class="input-group">
            <text class="input-label">设置密码</text>
            <input 
              class="input-field" 
              type="password" 
              v-model="registerForm.password"
              placeholder="请设置6-20位密码"
            />
          </view>
          <view class="input-group">
            <text class="input-label">确认密码</text>
            <input 
              class="input-field" 
              type="password" 
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
            />
          </view>
          <view class="agreement">
            <checkbox 
              :checked="registerForm.agreed" 
              @tap="registerForm.agreed = !registerForm.agreed"
            ></checkbox>
            <text class="agreement-text">
              我已阅读并同意
              <text class="link">《用户协议》</text>
              和
              <text class="link">《隐私政策》</text>
            </text>
          </view>
          <button class="submit-btn" @tap="handleRegister">注 册</button>
        </view>
      </swiper-item>
    </swiper>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue';
	import userApi from '@/apis/user.js'
// 当前标签页
const currentTab = ref('login');

// 登录表单数据
const loginForm = reactive({
  email: '',
  password: ''
});

// 注册表单数据
const registerForm = reactive({
  email: '',
  code: '',
  password: '',
  confirmPassword: '',
  agreed: false
});

// 验证码倒计时
const countdown = ref(0);

// 邮箱格式验证
const validateEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

// 切换标签
const switchTab = (tab) => {
  currentTab.value = tab;
};

// 处理滑动切换
const handleSwiperChange = (e) => {
  currentTab.value = e.detail.current === 0 ? 'login' : 'register';
};

// ...existing code...

// 发送验证码处理函数

const handleSendCode = async() => {
  try {
    // 表单验证
    if (!registerForm.email) {
      uni.showToast({
        title: '请输入邮箱',
        icon: 'none'
      });
      return;
    }

    if (!validateEmail(registerForm.email)) {
      uni.showToast({
        title: '邮箱格式不正确',
        icon: 'none'
      });
      return;
    }

    // 如果正在倒计时，阻止重复发送
    if (countdown.value > 0) {
      return;
    }

    uni.showLoading({
      title: '发送中...'
    });

    // 调用发送验证码API
    const res = await userApi.sendCode({
      email: registerForm.email  // 修改这里，传入对象格式
    });
    console.log(res)

    if (res.statusCode === 200) {  // 修改判断条件
      uni.hideLoading();
      uni.showToast({
        title: '验证码已发送',
        icon: 'success'
      });
      
      // 开始倒计时
      countdown.value = 60;
      const timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      throw new Error(res.data?.error || '验证码发送失败');
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none',
      duration: 2000
    });
  }
};

// 处理登录
const handleLogin = async() => {
  if (!loginForm.email || !loginForm.password) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }

  if (!validateEmail(loginForm.email)) {
    uni.showToast({
      title: '请输入正确的邮箱格式',
      icon: 'none'
    });
    return;
  }
 
  try{
    // 调用登入 api
  const loginData = {
    email: loginForm.email,
    password: loginForm.password
  }
   uni.showLoading({
    title: '登录中...'
  });
  const loginRes = await userApi.login(loginData)
  uni.hideLoading();
  console.log(loginRes)
  if(loginRes.statusCode === 200){
    uni.showToast({
      title:'登入成功',
      icon:'success'
    })

  }
  else{
    if (loginRes.statusCode === 401) {
      throw new Error('邮箱或密码错误，请重试');
    } else {
      throw new Error(loginRes.data?.error || '登录失败，请稍后重试');
    }
  }
  }catch(error){
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none',
      duration: 2000
    });

  }
 
 

};




// 处理注册

const handleRegister = async() => {
  if (!registerForm.email || !registerForm.code || !registerForm.password || !registerForm.confirmPassword) {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none'
    });
    return;
  }

  if (!validateEmail(registerForm.email)) {
    uni.showToast({
      title: '请输入正确的邮箱格式',
      icon: 'none'
    });
    return;
  }

  if (registerForm.password !== registerForm.confirmPassword) {
    uni.showToast({
      title: '两次密码不一致',
      icon: 'none'
    });
    return;
  }

  if (!registerForm.agreed) {
    uni.showToast({
      title: '请同意用户协议',
      icon: 'none'
    });
    return;
  }



const registerData = {
  email: registerForm.email,
  password: registerForm.password,
  code: registerForm.code,
  username: registerForm.email.split('@')[0]
}
try {
  // ...保持原有的验证和数据构造代码...

  uni.showLoading({
    title: '注册中...'
  });

  // 调用注册 API
  const registerRes = await userApi.register(registerData);
  console.log(registerRes)
  // 根据接口返回处理结果
  if (registerRes.statusCode === 200) {
    uni.hideLoading();
    uni.showToast({
      title: '注册成功',
      icon: 'success'
    });
    // 注册成功后切换到登录页并清空表单
    currentTab.value = 'login';
    Object.assign(registerForm, {
      email: '',
      code: '',
      password: '',
      confirmPassword: '',
      agreed: false
    });
  } else {
    // 抛出错误，让 catch 统一处理
    throw new Error(registerRes.data.error || '注册失败，请稍后重试');
  }

} catch (error) {
  uni.hideLoading();
  // 显示具体的错误信息
  uni.showToast({
    title: error.message || '注册失败，请重试',
    icon: 'none',
    duration: 2000  // 显示2秒
  });
}

}
;
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background-color: #fff;
}

/* 顶部背景 */
.login-header {
  position: relative;
  height: 300rpx; /* 减小顶部高度 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx; /* 减小内边距 */
}

.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.header-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(255,255,255,0.9), rgba(255,255,255,1));
  z-index: 2;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
  z-index: 3;
}

.slogan {
  font-size: 36rpx;
  color: #333;
  font-weight: 500;
  z-index: 3;
}

/* 切换标签 */
.tab-container {
  display: flex;
  position: relative;
  padding: 0 60rpx;
  margin-bottom: 20rpx; /* 减小底部间距 */
}

.tab-item {
  flex: 1;
  display: flex;
  justify-content: center;
  padding: 20rpx 0;
}

.tab-item text {
  font-size: 32rpx;
  color: #999;
  transition: color 0.3s;
}

.tab-item.active text {
  color: #333;
  font-weight: 500;
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 60rpx;
  width: calc(50% - 60rpx);
  height: 4rpx;
  background: linear-gradient(to right, #FF9A9E, #FAD0C4);
  transition: transform 0.3s;
}

/* 表单区域 */
.form-swiper {
  height: calc(100vh - 580rpx); /* 调整高度为剩余可视区域 */
}

.form-container {
  height: 100%;
  padding: 0 60rpx;
  overflow-y: auto; /* 添加滚动 */
  -webkit-overflow-scrolling: touch; /* 优化iOS滚动 */
}

.input-group {
  margin-bottom: 40rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.input-field {
  width: 100%;
  height: 90rpx;
  background: #f8f8f8;
  border-radius: 45rpx;
  padding: 0 40rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.verification {
  display: flex;
  gap: 20rpx;
}

.verify-btn {
  width: 200rpx;
  height: 90rpx;
  line-height: 90rpx;
  background: rgba(255, 154, 158, 0.1);
  border: 2rpx solid #FF9A9E;
  border-radius: 45rpx;
  font-size: 26rpx;
  color: #FF9A9E;
  text-align: center;
  padding: 0;
  transition: all 0.3s ease;
}

.verify-btn[disabled] {
  background: #f5f5f5;
  border-color: #ddd;
  color: #999;
}

.verify-btn:active {
  transform: scale(0.98);
  opacity: 0.8;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 40rpx;
}

.forget-pwd {
  font-size: 26rpx;
  color: #999;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background: linear-gradient(135deg, #FF9A9E 0%, #FF5758 100%);
  box-shadow: 0 8rpx 20rpx rgba(255, 87, 88, 0.3);
  border-radius: 45rpx;
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 60rpx;
  border: none;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.submit-btn::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to right, rgba(255,255,255,0.1), rgba(255,255,255,0.3));
  opacity: 0;
  transition: opacity 0.3s ease;
}

.submit-btn:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 10rpx rgba(255, 87, 88, 0.2);
}

.submit-btn:active::after {
  opacity: 1;
}

.agreement {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.agreement-text {
  font-size: 26rpx;
  color: #999;
  margin-left: 12rpx;
}

.link {
  color: #FF9A9E;
}

/* 其他登录方式 */
.other-login {
  margin-top: 60rpx;
}

.divider {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1rpx;
  background: #eee;
}

.divider-text {
  padding: 0 30rpx;
  font-size: 26rpx;
  color: #999;
  background: #fff;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 80rpx;
}

.social-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.social-item image {
  width: 80rpx;
  height: 80rpx;
  margin-bottom: 12rpx;
}

.social-item text {
  font-size: 26rpx;
  color: #666;
}
</style> 